const { readdirSync, statSync } = require('fs');
const { resolve } = require('path');

const pageConfig = {};
const tabNavs = [];
const pageNames = readdirSync(resolve(__dirname, '..', 'src/pages'))
  .filter((name) => statSync(resolve(__dirname, '..', 'src/pages', name)).isDirectory())
  .filter((name) => name !== 'common' || name !== 'index')
  .sort((a, b) => {
    if (a.indexOf('.') > 0) return 1;
    if (b.indexOf('.') > 0) return -1;
    return a.length > b.length ? 1 : -1;
  })
  .map((name) => {
    try {
      const config = require(resolve(__dirname, '..', 'src/pages', name, 'config.json'));
      
      if (config.$extend) {
        if (config.$extend.tabNavIndex && config.$extend.tabNavIndex in pageConfig) {
          config.tabNavIndex = pageConfig[config.$extend.tabNavIndex].nav;
          config.isTabNav = false;
        }

        delete config.$extend;
      } else {
        if (config.tabNavIndex) {
          config.isTabNav = true;
        }
      }

      config.name = name;
      pageConfig[name] = config;

      if (config.isTabNav) {
        tabNavs.push(config);
      }
    } catch {}

    return name;
  });

tabNavs.sort((a, b) => a.tabNavIndex - b.tabNavIndex);

module.exports = { pageConfig, tabNavs, pageNames };